package base62

import (
	"errors"
	"math"
	"strings"
)

var (
	basestr string
)

func MustInit(bs string) error {
	if bs == "" {
		return errors.New("need base string")
	}
	basestr = bs
	return nil
}
func Transport62(req uint64) string {
	if req == 0 {
		return string(basestr[0])
	}
	var data []byte
	for req > 0 {
		t := req % 62
		div := req / 62
		data = append(data, basestr[t])
		req = div
	}
	return string(reverse(data))
}
func Transport62Reverse(req string) (seq uint64) {
	bl := []byte(req)
	bl = reverse(bl)
	for idx, v := range bl {
		base := math.Pow(62, float64(idx))
		seq += uint64(strings.Index(basestr, string(v))) * uint64(base)
	}
	return
}

func reverse(data []byte) []byte {
	for i, j := 0, len(data)-1; i < len(data)/2; i, j = i+1, j-1 {
		data[i], data[j] = data[j], data[i]
	}
	return data
}
